package cn.hnu.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * Redis工具类，封装常用的Redis操作
 */
@Component
public class RedisUtil {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 设置缓存
     */
    public void set(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);
    }

    /**
     * 设置缓存并指定过期时间
     */
    public void set(String key, Object value, long timeout, TimeUnit unit) {
        redisTemplate.opsForValue().set(key, value, timeout, unit);
    }

    /**
     * 获取缓存
     */
    public Object get(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 删除缓存
     */
    public Boolean delete(String key) {
        return redisTemplate.delete(key);
    }

    /**
     * 判断key是否存在
     */
    public Boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }

    /**
     * 设置过期时间
     */
    public Boolean expire(String key, long timeout, TimeUnit unit) {
        return redisTemplate.expire(key, timeout, unit);
    }

    /**
     * 获取剩余过期时间
     */
    public Long getExpire(String key, TimeUnit unit) {
        return redisTemplate.getExpire(key, unit);
    }

    /**
     * 存储验证码（5分钟过期）
     */
    public void storeVerificationCode(String email, String code) {
        String key = "verification:code:" + email;
        set(key, code, 5, TimeUnit.MINUTES);
    }

    /**
     * 获取验证码
     */
    public String getVerificationCode(String email) {
        String key = "verification:code:" + email;
        return (String) get(key);
    }

    /**
     * 存储用户token
     */
    public void storeUserToken(Long userId, String token) {
        String key = "user:token:" + userId;
        set(key, token, 7, TimeUnit.DAYS);
    }

    /**
     * 检查用户token是否存在
     */
    public boolean checkUserToken(Long userId, String token) {
        String key = "user:token:" + userId;
        String storedToken = (String) get(key);
        return token.equals(storedToken);
    }

    /**
     * 设置key的值，并且指定过期时间，单位秒
     */
    public void set(String key, Object value, int time) {
        redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
    }
}